<template>
  <el-container class="shop-cart">
    <el-header class="profile-header">
      <h1 @click="goToHome" class="home">XX网购物平台</h1>
      <div class="user-info">
        <el-button type="default" @click="goToProfile" icon="el-icon-user" class="profileButton">
          个人中心
        </el-button>
        <el-button type="default" @click="goToOrders" icon="el-icon-document" class="orderButton">
          我的订单
        </el-button>
      </div>
    </el-header>
    <el-main class="cart-main">
      <el-table :data="cartItems">
        <el-table-column prop="cartId" label="ID" align="center" width="0" v-if="false">
          <template slot-scope="scope">
            <span style="color: red;font-weight: bold;font-size: 20px">{{ scope.row.cartId }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="image" label="图片">
          <template slot-scope="scope">
            <img :src="scope.row.productImage" class="product-image" alt="商品图片">
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="名称"></el-table-column>
        <el-table-column prop="price" align="center" label="价格">
          <template slot-scope="scope">
            <span style="color: red;font-weight: bold;font-size: 15px">¥ {{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" align="center">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.quantity" :min="1" size="small"
                             @change="updateQuantity(scope.row)"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="金额" align="center">
          <template slot-scope="scope">
            <span style="color: red;font-weight: bold;font-size: 20px">¥ {{
                scope.row.price * scope.row.quantity
              }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="checkoutItem(scope.row)">结算</el-button>
            <el-button size="mini" type="danger" @click="removeItem(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="cart-summary">
        <span>总数量：{{ totalQuantity }}</span>
        <span style="color: red;font-weight: bold;font-size: 25px">总价：¥ {{ totalPrice }}</span>
        <el-button type="primary" @click="checkoutAll">全部结算</el-button>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import {cartsList, updateCartItem, deleteCartItem, addOrder, deleteAllCartItem} from "@/api/cartsApi";


export default {
  name: 'ShopCart',
  data() {
    return {
      cartItems: [],
      totalQuantity: 0,
      totalPrice: 0,
    };
  },
  created() {
    this.fetchCartItems();
  },
  methods: {
    fetchCartItems() {
      cartsList().then(response => {
        console.log(response.data);
        this.cartItems = response.data;
        this.updateTotals();
      });
    },
    updateQuantity(item) {
      // 调用后端接口更新购物车数量
      updateCartItem(item.cartId, item.quantity).then(response => {
        console.log('Quantity updated:', response.data);
        this.updateTotals();
      }).catch(error => {
        console.error('Error updating quantity:', error);
        // 如果更新失败，恢复原数量
        this.$set(item, 'quantity', item.quantity);
      });
    },
    updateTotals() {
      this.totalQuantity = this.cartItems.reduce((sum, item) => sum + item.quantity, 0);
      this.totalPrice = this.cartItems.reduce((sum, item) => sum + item.price * item.quantity, 0);
    },
    checkoutItem(item) {
      // 将单个item包装成一个列表
      const itemList = [item];
      addOrder(itemList).then(response => {
        console.log('Order created:', response.data);
        // this.removeItem(item);
      });
      console.log('Checking out item:', item);
      // Implement checkout logic here
    },
    removeItem(item) {
      deleteCartItem(item.cartId)
      this.cartItems = this.cartItems.filter(i => i !== item);
      this.updateTotals();
    },
    checkoutAll() {
      addOrder(this.cartItems).then(response => {
        console.log('商品购买成功:', response.data);
        this.cartItems = [];
        this.updateTotals();
      });
      deleteAllCartItem().then(response => {
        console.log('购物车已清空:', response.data);
      });
      // Implement checkout all logic here
    },
    goToProfile() {
      if (this.$route.path !== '/shopProfile') {
        this.$router.push('/shopProfile');
      }
    },
    goToOrders() {
      if (this.$route.path !== '/shopOrder') {
        this.$router.push('/shopOrder');
      }
    },
    goToHome() {
      if (this.$route.path !== '/shop') {
        this.$router.push('/shop');
      }
    },
  },
  watch: {
    'cartItems': {
      handler: 'updateTotals',
      deep: true
    }
  }
};
</script>

<style scoped>
.shop-cart {
  font-family: Arial, sans-serif;
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: powderblue; /* 淡蓝色背景 */
}

.user-info {
  display: flex;
  align-items: center;
}

.cart-main {
  padding: 20px 200px;
}

.product-image {
  width: 100px;
  height: auto;
}

.cart-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: #f8f8f8;
}

.el-button {
  margin-right: 10px;
}

.profileButton, .orderButton {
  color: #409EFF; /* 更改文字颜色 */
}

.profileButton i, .orderButton i {
  color: #66baff; /* 图标颜色 */
}

.home {
  cursor: pointer; /* 添加手型光标 */
}
</style>